package com.black.play.listener.mouse;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author ylx
 */
public class DragListener extends MouseAdapter {

    private final Point currentMouseOffset = new Point();

    private final Component component;

    public DragListener(Component component) {
        this.component = component;
    }

    @Override
    public void mousePressed(MouseEvent e) {
        // 获取当前点击位置
        currentMouseOffset.x = e.getX();
        currentMouseOffset.y = e.getY();
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        // 获取主窗口当前位置坐标
        Point currentPoint = component.getLocationOnScreen();
        // 计算鼠标相对于点击时的偏移量作为窗口偏移量
        currentPoint.x += e.getX() - currentMouseOffset.x;
        currentPoint.y += e.getY() - currentMouseOffset.y;
        // 重新定位窗口
        component.setLocation(currentPoint);
    }
}
